import { useState, useEffect, useRef } from "react";
import { Card, Typography, Button, Space, message, Modal } from "antd";

const { Title } = Typography;

const Logs = () => {
  const [logOutput, setLogOutput] = useState("");
  const [modalVisible, setModalVisible] = useState(false);
  const scrollRef = useRef(null);
  const modalScrollRef = useRef(null);

  useEffect(() => {
    const ws = new WebSocket('ws://localhost:3002')

    ws.onmessage = event => {
      setLogOutput(prev => {
        const updated = prev + event.data
        localStorage.setItem('frp-log-cache', updated)
        return updated
      })
    }

    ws.onerror = err => {
      console.error('WebSocket 错误:', err)
    }
    
    // 初始加载缓存
    const savedLog = localStorage.getItem('frp-log-cache')
    if (savedLog) setLogOutput(savedLog)

    return () => {
      ws.close()
    }
  }, []);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
    if (modalVisible && modalScrollRef.current) {
      modalScrollRef.current.scrollTop = modalScrollRef.current.scrollHeight;
    }
  }, [logOutput, modalVisible]);

  const handleClear = () => setLogOutput("");
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(logOutput);
      message.success("日志已复制到剪贴板");
    } catch {
      message.error("复制失败");
    }
  };
  const handleExport = () => {
    if (!logOutput) {
      message.warning("日志为空，无法导出");
      return;
    }
    const blob = new Blob([logOutput], { type: "text/plain;charset=utf-8" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "frpc.log";
    a.click();
    window.URL.revokeObjectURL(url);
    message.success("日志导出成功");
  };

  return (
    <div style={{ maxWidth: 900, margin: "0 auto", padding: 20 }}>
      <Title level={4}>FRP 日志</Title>
      <Card
        bordered
        extra={
          <Space>
            <Button onClick={handleClear}>清空</Button>
            <Button onClick={handleCopy}>复制日志</Button>
            <Button type="primary" onClick={handleExport}>
              导出日志文件
            </Button>
            <Button onClick={() => setModalVisible(true)}>全屏查看</Button>
          </Space>
        }
      >
        <pre
          ref={scrollRef}
          style={{
            backgroundColor: "#111",
            color: "#0f0",
            fontFamily: "monospace",
            padding: 12,
            height: 400,
            overflowY: "auto",
            whiteSpace: "pre-wrap",
            borderRadius: 4,
          }}
        >
          {logOutput || "暂无日志输出..."}
        </pre>
      </Card>

      <Modal
        title="日志全屏查看"
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width="90vw"
        style={{ top: 20 }}
        bodyStyle={{ padding: 12, backgroundColor: "#111", color: "#0f0" }}
      >
        <pre
          ref={modalScrollRef}
          style={{
            fontFamily: "monospace",
            height: "70vh",
            overflowY: "auto",
            whiteSpace: "pre-wrap",
            margin: 0,
            color: "#0f0",
          }}
        >
          {logOutput || "暂无日志输出..."}
        </pre>
      </Modal>
    </div>
  );
};

export default Logs;
